import java.util.Comparator;
import java.util.*;

public class Text{
    public int[] topKFrequent(int[] nums, int k) {
        HashMap<Integer,Integer> hashmap = new HashMap<>();
        for(int num:nums) {
            hashmap.put(num,hashmap.getOrDefault(num,0)+1);
        }
        PriorityQueue<Map.Entry<Integer,Integer>> queue = new PriorityQueue<>(new Comparator<Map.Entry<Integer,Integer>>() {
            public int compare(Map.Entry<Integer,Integer> o1,Map.Entry<Integer,Integer> o2) {
                return o2.getValue() - o1.getValue();
            }
        });
        Set<Map.Entry<Integer,Integer>> entrys = hashmap.entrySet();
        for(Map.Entry<Integer,Integer> entry : entrys) {
            queue.offer(entry);
        }
        int[] ret = new int[k];
        for(int i = 0;i<k;i++) {
            ret[i] = queue.poll().getKey();
        }
        return ret;
    }
    public int[] getLeastNumbers(int[] arr, int k) {
        int[] array = new int[k];
        if(k == 0) {
            return array;
        }
        PriorityQueue<Integer> queue = new PriorityQueue<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1,Integer o2) {
                return o2-o1;
            }
        });
        for(int i = 0; i< k;i++) {
            queue.offer(arr[i]);
        }
        for(int i = k;i < arr.length;i++) {
            if(queue.peek() > arr[i]) {
                queue.poll();
                queue.offer(arr[i]);
            }
        }
        for(int n=0;n<k;n++) {
            array[n] = queue.poll();
        }
        return array;
    }
    public static void main(String[] args) {
    }
}
